package com.controller.user;

import com.common.ErrorCodeEnum;
import com.common.anntation.Log;
import com.common.emums.BusinessType;
import com.common.exception.BusinessException;
import com.common.redis.RedisCache;
import com.common.utils.Md5Utils;
import com.common.utils.PasswordUtils;
import com.common.utils.StringUtils;
import com.core.sms.service.SmsServer;
import com.core.springSecurity.authentication.PasswordAuthenticationToken;
import com.core.springSecurity.common.SecurityUtils;
import com.core.springSecurity.service.SysLoginService;
import com.core.springSecurity.service.TokenService;
import com.model.base.Result;
import com.model.dto.user.baseInfo.UpdatePwdDTO;
import com.model.pojo.sys.SysUser;
import com.service.sys.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Api(tags = {"用户信息"})
@Slf4j
@RestController
@RequestMapping("/v1/user/baseInfo")
@RequiredArgsConstructor
public class UserBaseInfoController {
    private final RedisCache redisCache;
    private final TokenService tokenService;
    private final SysLoginService sysLoginService;
    private final SysUserService sysUserService;
    private final AuthenticationManager authenticationManager;
    @ApiOperation(value = "修改密码")
    @PostMapping("/updatePwd")
    public Result<Objects> updatePwd(@RequestBody @Valid UpdatePwdDTO dto) {
        long userId = SecurityUtils.getLoginUser().getUser().getSysUserId();
        SysUser sysUser = sysUserService.get(userId);
        if (sysUser == null) {
            return Result.fail("9999", "用户未登录或不存在");
        }
        Authentication authentication;
        try {
            String password = Md5Utils.toUpperCase32(dto.getOldPwd());
            authentication = authenticationManager
                    .authenticate(new PasswordAuthenticationToken(sysUser.getName(), password));
        } catch (BusinessException e) {
            return Result.fail("9999", "原密码错误");
        }
        if (StringUtils.isNull(authentication)) {
            return Result.fail("9999", "原密码错误");
        }
        sysUser.setPassword(PasswordUtils.encode(Md5Utils.toUpperCase32(dto.getNewPwd())));
        sysUserService.update(sysUser);
        return Result.suc();
    }
}
